package com.dream.wukong.common.core.util;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: wuyichao
 * @Description:
 * @Date: Created in 10:25 2018/9/19.
 * @Modified:
 */
public class ThreadLocalCache {
    private ThreadLocalCache() {}

    private static ThreadLocal threadLocal = new ThreadLocal();

    public static <T> void put(String key, T t) {
        Map map = (Map)threadLocal.get();
        if(map == null) {
            map = new HashMap();
            threadLocal.set(map);
        }
        map.put(key, t);
    }

    public static <T> T get(String key) {
        Map map = (Map)threadLocal.get();
        T object = null;
        if(map != null) {
            object = (T)map.get(key);
        }
        return object;
    }

    public static void clean() {
        threadLocal.set(null);
    }

    public static void print() {
        System.out.println("------------------------[ThreadLocalCache]------------------------");
        System.out.println("Current Thread: " + Thread.currentThread().getId() + "/" + Thread.currentThread().getName());
        Map map = (Map)threadLocal.get();
        if(map != null) {
            System.out.println("map size:" + map.size());
        } else {
            System.out.println("map = null");
        }
        System.out.println("------------------------[ThreadLocalCache]------------------------");
    }
}
